import type { DirectiveBinding } from 'vue'

/**
 * 自定义指令：按钮点击节流
 * 用法：
 * <button v-throttle-click:2000 @click="yourMethod">点击</button>
 */

export default {
  mounted(el: any, binding: DirectiveBinding<Function>) {
    let throttling = false
    const delay = binding.arg ? Number(binding.arg) : 2000

    el.__throttleHandler__ = async (...args: any[]) => {
      if (throttling) return
      throttling = true
      el.disabled = true

      try {
        const result = binding.value?.(...args)
        if (result instanceof Promise) {
          await result
        }
      } finally {
        setTimeout(() => {
          throttling = false
          el.disabled = false
        }, delay)
      }
    }
  },
  beforeUnmount(el: any) {
    delete el.__throttleHandler__
  }
}